//
// Copyright (C) 2011 - 2013  Steve Channell steve.channell@cepheis.com
//
// This file is part of Cephei.QL, an open-source library wrapper 
// arround QuantLib http://quantlib.org/
//
// Cephei.QL is open source software: you can redistribute it and/or modify it
// under the terms of the license.  You should have received a
// copy of the license along with this program; if not, please email
// <support@cepheis.com>. The license is also available online at
// <http://cepheis.com/license.htm>.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE.  See the license for more details.
//
// Version 2.2 with QuantLib 1.2.1
//#include "stdafx.h"
#include "CdsOption.h"
using namespace Cephei::QL::Experimental::Credit;
#include <gen/QL/Instruments/CreditDefaultSwap.h>
#include <gen/QL/Exercise.h>
#include <gen/QL/Termstructures/YieldTermStructure.h>
#include <gen/QL/Termstructures/DefaultProbabilityTermStructure.h>
#include <gen/QL/Payoff.h>
#include <gen/QL/PricingEngine.h>
#include <gen/QL/Option.h>
using namespace Cephei::QL::Instruments;
using namespace Cephei::QL;
using namespace Cephei::QL::Termstructures;
#define HANDLE
#undef ABSTRACT
#undef STRUCT
Cephei::QL::Experimental::Credit::CCdsOption::CCdsOption (Cephei::QL::Instruments::ICreditDefaultSwap^ swap, Cephei::QL::IExercise^ exercise, Microsoft::FSharp::Core::FSharpOption<Boolean>^ knocksOut, Cephei::QL::IPricingEngine^ QL_Pricer) : COption(CCdsOption::typeid)
{
    CCreditDefaultSwap^ _Cswap;
    CExercise^ _Cexercise;
    try
    {
#ifdef HANDLE
        _phCdsOption = NULL;
#endif
        _Cswap = safe_cast<CCreditDefaultSwap^> (swap);
        _Cswap->Lock();
        boost::shared_ptr<QuantLib::CreditDefaultSwap>& _swap = static_cast<boost::shared_ptr<QuantLib::CreditDefaultSwap>&> (_Cswap->GetShared ()); 
        _Cexercise = safe_cast<CExercise^> (exercise);
        _Cexercise->Lock();
        boost::shared_ptr<QuantLib::Exercise>& _exercise = static_cast<boost::shared_ptr<QuantLib::Exercise>&> (_Cexercise->GetShared ()); 
        bool _knocksOut = 
            (Microsoft::FSharp::Core::FSharpOption<Boolean>::IsSome::get (knocksOut) ? (bool)ValueHelper::Convert (knocksOut->Value) : true); //4
        _ppCdsOption = new boost::shared_ptr<QuantLib::CdsOption> (new QuantLib::CdsOption ( _swap,  _exercise,  _knocksOut ));
        CPricingEngine^ _CQL_Pricer = safe_cast<CPricingEngine^> (QL_Pricer);
        boost::shared_ptr<QuantLib::PricingEngine>& _QL_Pricer = static_cast<boost::shared_ptr<QuantLib::PricingEngine>&> (_CQL_Pricer->GetShared ());
        (*_ppCdsOption)->setPricingEngine (_QL_Pricer);
        SetOption (boost::dynamic_pointer_cast<QuantLib::Option> (*_ppCdsOption));
	}
    catch (QuantLib::Error& _error)
    {
        if (_error.what())
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String(_error.what()));
        else
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String("Unknown quantlib error"));
        
    }
	catch (std::exception& _error)
	{
        if (_error.what())
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String(_error.what()));
        else
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String("Unknown std::exception"));
	}
    finally
    {
        if (_Cswap != nullptr) _Cswap->Unlock();
        if (_Cexercise != nullptr) _Cexercise->Unlock();
    }
}
Cephei::QL::Experimental::Credit::CCdsOption::CCdsOption (boost::shared_ptr<QuantLib::CdsOption>& childNative, Object^ owner) : COption(CCdsOption::typeid)
{
#ifdef HANDLE
	_phCdsOption = NULL;
#endif
	_ppCdsOption = &childNative;
    _ppOption = new boost::shared_ptr<QuantLib::Option> (boost::dynamic_pointer_cast<QuantLib::Option> (*_ppCdsOption));
}
Cephei::QL::Experimental::Credit::CCdsOption::CCdsOption (QuantLib::CdsOption& childNative, Object^ owner) : COption(CCdsOption::typeid)
{
#ifdef HANDLE
	_phCdsOption = NULL;
#endif
	_ppCdsOption = new boost::shared_ptr<QuantLib::CdsOption> (&childNative);
    _ppOption = new boost::shared_ptr<QuantLib::Option> (boost::dynamic_pointer_cast<QuantLib::Option> (*_ppCdsOption));
    _CdsOptionOwner = owner;
    _OptionOwner = owner;
}

Cephei::QL::Experimental::Credit::CCdsOption::CCdsOption (CCdsOption^ copy) : COption(CCdsOption::typeid)
{
#ifdef HANDLE
	_phCdsOption = NULL;
#endif
	if (copy->HasNative() != NULL)
    {
		_ppCdsOption = new boost::shared_ptr<QuantLib::CdsOption> (copy->GetShared());
        _ppOption = new boost::shared_ptr<QuantLib::Option> (boost::dynamic_pointer_cast<QuantLib::Option> (*_ppCdsOption));
    }
}
Cephei::QL::Experimental::Credit::CCdsOption::CCdsOption (PLATFORM::Type^ t) : COption(CCdsOption::typeid)
{
#ifdef HANDLE
	_phCdsOption = NULL;
#endif
	if (!t->IsSubclassOf(CCdsOption::typeid))
		throw REFNEW Exception ("Invalid base-case init");
}
#ifdef HANDLE
Cephei::QL::Experimental::Credit::CCdsOption::CCdsOption (QuantLib::Handle<QuantLib::CdsOption>& childNative, Object^ owner)  : COption(CCdsOption::typeid)
{
	_phCdsOption = &childNative;
	_ppCdsOption = &static_cast<boost::shared_ptr<QuantLib::CdsOption>>(childNative.currentLink());
    _ppOption = new boost::shared_ptr<QuantLib::Option> (boost::dynamic_pointer_cast<QuantLib::Option> (*_ppCdsOption));
    _CdsOptionOwner = owner;
}
Cephei::QL::Experimental::Credit::CCdsOption::CCdsOption (QuantLib::Handle<QuantLib::CdsOption> childNative)  : COption(CCdsOption::typeid)
{
	_phCdsOption = &childNative;
	_ppCdsOption = &static_cast<boost::shared_ptr<QuantLib::CdsOption>>(childNative.currentLink());
    _ppOption = new boost::shared_ptr<QuantLib::Option> (boost::dynamic_pointer_cast<QuantLib::Option> (*_ppCdsOption));
}
#endif
#ifdef STRUCT
Cephei::QL::Experimental::Credit::CCdsOption::CCdsOption (QuantLib::CdsOption childNative)  : COption(CCdsOption::typeid)
{
#ifdef HANDLE
	_phCdsOption = NULL;
#endif
	_ppCdsOption = new boost::shared_ptr<QuantLib::CdsOption> (new QuantLib::CdsOption (childNative));
    _ppOption = new boost::shared_ptr<QuantLib::Option> (boost::dynamic_pointer_cast<QuantLib::Option> (*_ppCdsOption));
}
#endif

Cephei::QL::Experimental::Credit::CCdsOption::~CCdsOption ()
{
    if (_ppCdsOption != NULL)
    {
	    delete _ppCdsOption;
        _ppCdsOption = NULL;
    }
}
Cephei::QL::Experimental::Credit::CCdsOption::!CCdsOption ()
{
    if (_ppCdsOption != NULL)
    {
	    delete _ppCdsOption;
    }
}
QuantLib::CdsOption& Cephei::QL::Experimental::Credit::CCdsOption::GetReference ()
{
    if (_ppCdsOption == NULL) throw REFNEW NativeNullException ();
	return **_ppCdsOption;
}
boost::shared_ptr<QuantLib::CdsOption>& Cephei::QL::Experimental::Credit::CCdsOption::GetShared ()
{
    if (_ppCdsOption == NULL) throw REFNEW NativeNullException ();
	return *_ppCdsOption;
}
QuantLib::CdsOption* Cephei::QL::Experimental::Credit::CCdsOption::GetPointer ()
{
    if (_ppCdsOption == NULL) throw REFNEW NativeNullException ();
	return &**_ppCdsOption;
}
#ifdef HANDLE
QuantLib::Handle<QuantLib::CdsOption>& Cephei::QL::Experimental::Credit::CCdsOption::GetHandle ()
{
	if (_phCdsOption == NULL)
	{
		_phCdsOption = new Handle<QuantLib::CdsOption> (*_ppCdsOption);
	}
	return *_phCdsOption;
}
#endif
bool Cephei::QL::Experimental::Credit::CCdsOption::HasNative () 
{
	return (_ppCdsOption != NULL);
}

Boolean Cephei::QL::Experimental::Credit::CCdsOption::IsExpired::get ()
{
    try
    {
    	bool _rv = (bool)(*_ppCdsOption)->isExpired ( );   
        Boolean _nrv = (Boolean)ValueHelper::Convert (_rv); //c
    	return _nrv;
	}
    catch (QuantLib::Error& _error)
    {
        if (_error.what())
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String(_error.what()));
        else
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String("Unknown quantlib error"));
        
    }
	catch (std::exception& _error)
	{
        if (_error.what())
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String(_error.what()));
        else
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String("Unknown std::exception"));
	}
    finally
    {
    }
}
Double Cephei::QL::Experimental::Credit::CCdsOption::RiskyAnnuity::get ()
{
    try
    {
    	QuantLib::Real _rv = (QuantLib::Real)(*_ppCdsOption)->riskyAnnuity ( );   
        Double _nrv = (Double)ValueHelper::Convert (_rv); //c
    	return _nrv;
	}
    catch (QuantLib::Error& _error)
    {
        if (_error.what())
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String(_error.what()));
        else
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String("Unknown quantlib error"));
        
    }
	catch (std::exception& _error)
	{
        if (_error.what())
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String(_error.what()));
        else
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String("Unknown std::exception"));
	}
    finally
    {
    }
}
Double Cephei::QL::Experimental::Credit::CCdsOption::AtmRate::get ()
{
    try
    {
    	QuantLib::Rate _rv = (QuantLib::Rate)(*_ppCdsOption)->atmRate ( );   
        Double _nrv = (Double)ValueHelper::Convert (_rv); //c
    	return _nrv;
	}
    catch (QuantLib::Error& _error)
    {
        if (_error.what())
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String(_error.what()));
        else
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String("Unknown quantlib error"));
        
    }
	catch (std::exception& _error)
	{
        if (_error.what())
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String(_error.what()));
        else
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String("Unknown std::exception"));
	}
    finally
    {
    }
}
Double Cephei::QL::Experimental::Credit::CCdsOption::ImpliedVolatility (Double price, Cephei::QL::Termstructures::IYieldTermStructure^ termStructure, Cephei::QL::Termstructures::IDefaultProbabilityTermStructure^ probability, Double recoveryRate, Microsoft::FSharp::Core::FSharpOption<Double>^ accuracy, Microsoft::FSharp::Core::FSharpOption<UInt64>^ maxEvaluations, Microsoft::FSharp::Core::FSharpOption<Double>^ minVol, Microsoft::FSharp::Core::FSharpOption<Double>^ maxVol)
{
    CYieldTermStructure^ _CtermStructure;
    CDefaultProbabilityTermStructure^ _Cprobability;
    try
    {
        QuantLib::Real _price = (QuantLib::Real)ValueHelper::Convert (price); //a
        _CtermStructure = safe_cast<CYieldTermStructure^> (termStructure);
        _CtermStructure->Lock();
        Handle<QuantLib::YieldTermStructure>& _termStructure = static_cast<Handle<QuantLib::YieldTermStructure>&> (_CtermStructure->GetHandle ()); 
        _Cprobability = safe_cast<CDefaultProbabilityTermStructure^> (probability);
        _Cprobability->Lock();
        Handle<QuantLib::DefaultProbabilityTermStructure>& _probability = static_cast<Handle<QuantLib::DefaultProbabilityTermStructure>&> (_Cprobability->GetHandle ()); 
        QuantLib::Real _recoveryRate = (QuantLib::Real)ValueHelper::Convert (recoveryRate); //a
        QuantLib::Real _accuracy = 
            (Microsoft::FSharp::Core::FSharpOption<Double>::IsSome::get (accuracy) ? (QuantLib::Real)ValueHelper::Convert (accuracy->Value) : 1.e-4); //9a
        QuantLib::Size _maxEvaluations = 
            (Microsoft::FSharp::Core::FSharpOption<UInt64>::IsSome::get (maxEvaluations) ? (QuantLib::Size)ValueHelper::Convert (maxEvaluations->Value) : 100); //9a
        QuantLib::Volatility _minVol = 
            (Microsoft::FSharp::Core::FSharpOption<Double>::IsSome::get (minVol) ? (QuantLib::Volatility)ValueHelper::Convert (minVol->Value) : 1.0e-7); //9a
        QuantLib::Volatility _maxVol = 
            (Microsoft::FSharp::Core::FSharpOption<Double>::IsSome::get (maxVol) ? (QuantLib::Volatility)ValueHelper::Convert (maxVol->Value) : 4.0); //9a
    	QuantLib::Volatility _rv = (QuantLib::Volatility)(*_ppCdsOption)->impliedVolatility ( _price,  _termStructure,  _probability,  _recoveryRate,  _accuracy,  _maxEvaluations,  _minVol,  _maxVol );   
        Double _nrv = (Double)ValueHelper::Convert (_rv); //c
    	return _nrv;
	}
    catch (QuantLib::Error& _error)
    {
        if (_error.what())
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String(_error.what()));
        else
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String("Unknown quantlib error"));
        
    }
	catch (std::exception& _error)
	{
        if (_error.what())
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String(_error.what()));
        else
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String("Unknown std::exception"));
	}
    finally
    {
        if (_CtermStructure != nullptr) _CtermStructure->Unlock();
        if (_Cprobability != nullptr) _Cprobability->Unlock();
    }
}
Cephei::QL::Instruments::ICreditDefaultSwap^ Cephei::QL::Experimental::Credit::CCdsOption::UnderlyingSwap::get ()
{
    try
    {
    	boost::shared_ptr<QuantLib::CreditDefaultSwap>& _rv = (boost::shared_ptr<QuantLib::CreditDefaultSwap>&)(*_ppCdsOption)->underlyingSwap ( );   
        Cephei::QL::Instruments::CCreditDefaultSwap^ _nrv = REFNEW Cephei::QL::Instruments::CCreditDefaultSwap (_rv, this);
    	return _nrv;
	}
    catch (QuantLib::Error& _error)
    {
        if (_error.what())
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String(_error.what()));
        else
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String("Unknown quantlib error"));
        
    }
	catch (std::exception& _error)
	{
        if (_error.what())
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String(_error.what()));
        else
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String("Unknown std::exception"));
	}
    finally
    {
    }
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Factory class

Cephei::QL::Experimental::Credit::ICdsOption^ Cephei::QL::Experimental::Credit::CCdsOption_Factory::Create (Cephei::QL::Instruments::ICreditDefaultSwap^ swap, Cephei::QL::IExercise^ exercise, Microsoft::FSharp::Core::FSharpOption<Boolean>^ knocksOut, Cephei::QL::IPricingEngine^ QL_Pricer)
{
    return REFNEW CCdsOption ( swap,  exercise,  knocksOut,  QL_Pricer);
}
